package com.heima.wemedia.service.impl;


import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.aliyun.ImageAutoRoute;
import com.heima.common.aliyun.TextAutoRoute;
import com.heima.common.tess4j.tess4jClient;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import com.zxc.apis.article.IArticleClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.hbase.thirdparty.io.netty.util.internal.StringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Component
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {
    @Resource
    private WmNewsMapper wmNewsMapper;
    @Resource
    private WmNewsService wmNewsService;
    @Resource
    private TextAutoRoute textAutoRoute;
    @Resource
    private ImageAutoRoute imageAutoRoute;
    @Resource
    private WmChannelMapper wmChannelMapper;
    @Resource
    private WmUserServiceImpl wmUserService;
    @Resource
    private IArticleClient iArticleClient;
    @Resource
    private FileStorageService fileStorageService;
    @Resource
    private WmSensitiveMapper wmSensitiveMapper;
    @Resource
    private tess4jClient tess4jClient;

    @Override
    @Async
    public void autoScanWmNews(WmNews wmNews) {

        if (wmNews.getStatus().equals(WmNews.Status.SUBMIT.getCode())) {

            Map<String, Object> map = handleContentAndImage(wmNews);

            boolean isTextScan = true;
            if (!isTextScan) {
                return;
            }
            boolean isImageScan = handleImageScan((List<String>) map.get("image"),wmNews);
            if (!isImageScan) return;


            boolean isSensitive = handleSensitiveScan((String) map.get("content"), wmNews);
            if (!isSensitive) return;

            ResponseResult responseResult = saveArticle(wmNews);

            if (!responseResult.getCode().equals(200))
                throw new RuntimeException("WmNewsAutoScanServiceImpl===》保存app端相关文章数据失败");
            wmNews.setArticleId((Long) responseResult.getData());
            updateWmNews(wmNews, (short) 9, "审核成功");
        }


    }

    private boolean handleSensitiveScan(String content, WmNews wmNews) {
        boolean flag = true;
        List<WmSensitive> wmSensitives = wmSensitiveMapper.selectList(Wrappers.<WmSensitive>lambdaQuery().select(WmSensitive::getSensitives));
        List<String> words = wmSensitives.stream().map(WmSensitive::getSensitives).collect(Collectors.toList());
        SensitiveWordUtil.initMap(words);
        Map<String, Integer> map = SensitiveWordUtil.matchWords(content);
        if (CollectionUtils.isNotEmpty(map)) {
            updateWmNews(wmNews, (short) 2, "含有敏感词(" + map + ")");
            flag = false;
        }
        return flag;
    }

    private ResponseResult saveArticle(WmNews wmNews) {

        ArticleDto dto = new ArticleDto();
        BeanUtils.copyProperties(wmNews, dto);
        dto.setLayout(wmNews.getType());
        WmChannel wmChannel = wmChannelMapper.selectById(wmNews.getChannelId());
        if (wmChannel != null) dto.setChannelName(wmChannel.getName());
        dto.setAuthorId(wmNews.getUserId().longValue());
        WmUser wmUser = wmUserService.getById(wmNews.getUserId());
        if (wmUser != null) dto.setAuthorName(wmUser.getName());
        dto.setCreatedTime(new Date());
        if (wmNews.getArticleId() != null) dto.setId(wmNews.getArticleId());

        return iArticleClient.saveArticle(dto);

    }

    private boolean handleImageScan(List<String> images, WmNews wmNews) {
        boolean flag = true;
        if (images == null || images.isEmpty()) {
            return true;
        }
        try {
            images = images.stream().distinct().collect(Collectors.toList());
            for (String image : images) {
                byte[] bytes = fileStorageService.downLoadFile(image);

                ByteArrayInputStream in = new ByteArrayInputStream(bytes);
                BufferedImage bufferedImage = ImageIO.read(in);
                String content = tess4jClient.doDCR(bufferedImage);
                boolean isSensitive = handleSensitiveScan(content, wmNews);
                if (isSensitive) return true;
//                Map map = imageAutoRoute.imageScan(bytes);
//
//                if (map.get("label") != null && map.get("confidence") != null && (float) map.get("confidence") > 80) {
//                    flag = false;
//                    updateWmNews(wmNews, (short) 2, "文章中存在违规内容");
//                } else if (!map.get("label").equals("nonLabel")) {
//
//                    updateWmNews(wmNews, (short) 3, "文章中存在不确定内容");
                    flag = false;
//                }
            }
        } catch (Exception e) {
            flag = false;
            e.printStackTrace();

        }
        return flag;

    }

    private boolean handleTextScan(String content, WmNews wmNews) {

        boolean flag = true;
        try {
            if (StringUtil.isNullOrEmpty(content)) {
                return true;
            }
            Map map = textAutoRoute.greeTextScan(content + wmNews.getTitle());
            if (map.get("reason") == null || map.get("reason").equals("")) {
                updateWmNews(wmNews, (short) 9, "审核通过");

            }
            if (map.get("reason") != null && map.get("reason").toString().length() > 0) {
                updateWmNews(wmNews, (short) 3, "文章中存在不确定内容");
                flag = false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            flag = false;
        }
        return flag;
    }

    private void updateWmNews(WmNews wmNews, short status, String reason) {
        wmNews.setStatus(status);
        wmNews.setReason(reason);
        wmNewsMapper.updateById(wmNews);
    }

    private Map<String, Object> handleContentAndImage(WmNews wmNews) {
        if (StringUtils.isBlank(wmNews.getContent())) {
            throw new RuntimeException("WmNewsAutoScanServiceImpl==文章为空");
        }
        HashMap<String, Object> resultMap = new HashMap<>();
        StringBuilder stringBuilder = new StringBuilder();
        ArrayList<String> imagesList = new ArrayList<>();

        List<Map> maps = JSONArray.parseArray(wmNews.getContent(), Map.class);
        for (Map map : maps) {
            if (map.get("type").equals("text")) {
                stringBuilder.append(map.get("value"));
            }
            if (map.get("type").equals("image")) {
                imagesList.add((String) map.get("value"));
            }
        }
        if (StringUtils.isNotEmpty(wmNews.getImages())) {
            String[] images = wmNews.getImages().split(",");
            imagesList.addAll(Arrays.asList(images));
        }

        resultMap.put("content", stringBuilder.toString());
        resultMap.put("image", imagesList);
        return resultMap;
    }
}
